package com.magupe.push.log.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.magupe.push.common.entity.Log;
import com.magupe.push.log.service.LogService;

public class MybatisUtils {

	private static SqlSessionFactory sqlSessionFactory;
	private static ThreadLocal<SqlSession> threadLocal = new  ThreadLocal<SqlSession>();
    
    static{
    	InputStream is = null;
		try {
			is = Resources.getResourceAsStream("mybatis-config.xml");
			sqlSessionFactory = new  SqlSessionFactoryBuilder().build(is);  
		} catch (IOException e) {
			e.printStackTrace();
			throw  new  RuntimeException("读取配置文件失败");
		} finally{
			try {is.close();} catch (IOException e) {e.printStackTrace();}
		}       
	}
	
    private MybatisUtils() {}
    
    public static SqlSession openSession() {
    	SqlSession session = threadLocal.get();
    	if(session == null) {
    		session = sqlSessionFactory.openSession();
    		threadLocal.set(session);
    	}
    	
    	return session;
    }
    
    public static void closeSqlSession() {
    	SqlSession session = threadLocal.get();
    	if(session != null) {
        	session.close();
        	threadLocal.remove();
    	}
    } 
    
	public static void main(String[] args) {
		Log log = new Log();
		log.setId(IdGen.snowFlakeId());
		log.setMessage("{\"contentId\":\"com.magupe.push\",\"msgId\":373870742523084800,\"secret\":\"f988c38b94ec4e6fbf0115f12779ba09\",\"source\":\"client\"}");
		log.setPrompting("认证成功");
		log.setForward(false);
		log.setLocalAddress("\"/10.6.190.174:7000");
		log.setRemoteAddress("\"/10.6.190.174:54044");
		log.setPacket("com.magupe.push.common.protocol.request.AuthenticationRequestPacket");
		log.setCreateDate(new Date());
		log.setSecret("f988c38b94ec4e6fbf0115f12779ba09");
		log.setContentId("com.magupe.push");
		log.setMsgId(373870742523084800L);
		log.setSource("client");
		
		
		LogService logService = new LogService();
		logService.save(log);
	}
}
